<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="视频标题" prop="videoTitle">
        <el-input
          v-model="queryParams.videoTitle"
          placeholder="请输入视频标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['weblog:blogVideos:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['weblog:blogVideos:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['weblog:blogVideos:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['weblog:blogVideos:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="blogVideosList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" v-if="true"/>
      <el-table-column label="视频集ID" align="center" prop="catalogId" />
      <el-table-column label="视频标题" align="center" prop="videoTitle" />
      <el-table-column label="视频描述" align="center" prop="description" />
      <el-table-column label="视频的URL或文件路径" align="center" prop="url" />
      <el-table-column label="视频时长" align="center" prop="duration" />
      <el-table-column label="视频缩略图URL" align="center" prop="thumbnailUrl" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.thumbnailUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['weblog:blogVideos:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['weblog:blogVideos:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改视频管理对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="blogVideosRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="视频标题" prop="videoTitle">
          <el-input v-model="form.videoTitle" placeholder="请输入视频标题" />
        </el-form-item>
        <el-form-item label="视频描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="视频时长" prop="duration">
          <el-input v-model="form.duration" placeholder="请输入视频时长" />
        </el-form-item>

        <el-form-item label="视频来源" prop="videoType">
          <el-select
            v-model="form.videoType"
            placeholder="视频来源"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dict in blog_video_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="视频类型" prop="playType">
          <el-input v-model="form.playType" placeholder="请输入视频类型" />
        </el-form-item>
        <el-form-item label="url" prop="url" v-if="form.videoType == 1">
          <el-input v-model="form.url" placeholder="请输入url" />
        </el-form-item>

        <el-row>
          <el-col :span =12>
            <el-form-item label="缩略图" prop="thumbnailUrl">
              <image-upload-url :limit="1" v-model="form.thumbnailUrl"/>
            </el-form-item>
          </el-col>
          <el-col :span =12>
            <el-form-item label="视频上传" prop="md5" v-if="form.videoType == 0 && isEmpty(form.id)">
                <el-upload ref="videoUpload"
                           class="videoUploadCss"
                           :action="uploadUrl"
                           :headers="videoHeaders"
                           drag
                           :on-error="onError"
                           :before-upload="beforeUpload"
                           :before-remove="beforeRemove"
                           :auto-upload="true"
                           :limit="1"
                           :http-request="chunkedUpload"
                           :on-progress="onProgress"

                >
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                  <template #tip>
                    <div class="el-upload__tip">
                      <el-progress :percentage="uploadPercentage" status="success" style="width: 150px"></el-progress>
                    </div>
                  </template>

                </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BlogVideos">
import {
  listBlogVideos,
  getBlogVideos,
  delBlogVideos,
  addBlogVideos,
  updateBlogVideos,
  testUploadVideo
} from "@/api/weblog/blogVideos";

import {getCurrentInstance, onMounted, reactive, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import axios from "axios";
import SparkMD5 from 'spark-md5'
import {ElMessage} from "element-plus";
import {getToken} from "@/utils/auth";
import ImageUploadUrl from "@/components/ImageUploadUrl/index.vue";
import {isEmpty} from "@/utils/common";

const { proxy } = getCurrentInstance();
const { blog_video_type } = proxy.useDict("blog_video_type");
const blogVideosList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const route = useRoute();
const router = useRouter();
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadUrl = ref(baseUrl + "/weblog/blogVideos/upload"); // 上传文件服务器地址
const videoHeaders = ref({ Authorization: "Bearer " + getToken() });
const  uploadPromises=ref([])  // 记录并发上传分片的线程
const  uploadPercentage=ref(0) //上传进度
const videoUpload = ref()
const completedChunks = ref(0);   // 完成的分片数量
const totalChunks = ref(0);       // 分片总数
const  videoForm=ref({
  id:'',
  width:null,
  height:null,
  identifier:null,
  duration: null,  // 添加视频时长
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    catalogId: undefined,
    videoTitle: undefined,
    description: undefined,
    url: undefined,
    duration: undefined,
    thumbnailUrl: undefined,
  },
  rules: {
    id: [
      { required: true, message: "主键ID不能为空", trigger: "blur" }
    ],
    catalogId: [
      { required: true, message: "视频集ID不能为空", trigger: "blur" }
    ],
    videoTitle: [
      { required: true, message: "视频标题不能为空", trigger: "blur" }
    ],
    description: [
      { required: true, message: "视频描述不能为空", trigger: "blur" }
    ],
    duration: [
      { required: true, message: "视频时长不能为空", trigger: "blur" }
    ],
    thumbnailUrl: [
      { required: true, message: "视频缩略图URL不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询视频管理列表 */
function getList() {
  loading.value = true;
  listBlogVideos(queryParams.value).then(response => {
    blogVideosList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    catalogId: route.query.catalogId,
    videoTitle: null,
    description: null,
    url: null,
    duration: null,
    thumbnailUrl: null,
    createBy: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("blogVideosRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  completedChunks.value = 0;
  open.value = true;
  title.value = "添加视频管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _id = row.id || ids.value
  getBlogVideos(_id).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改视频管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["blogVideosRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateBlogVideos(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addBlogVideos(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除视频管理编号为"' + _ids + '"的数据项？').then(function() {
    loading.value = true;
    return delBlogVideos(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('weblog/blogVideos/export', {
    ...queryParams.value
  }, `blogVideos_${new Date().getTime()}.xlsx`)
}
onMounted(()=>{
  queryParams.value.catalogId = route.query.catalogId
  getList();
})



// 视频上传前操作，获取视频时长
async function beforeUpload(file) {
  // 创建 video 元素来获取视频的宽高和时长
  let video = document.createElement('video');
  video.src = URL.createObjectURL(file);
  video.preload = 'metadata';

  // 获取视频元数据（宽高和时长）
  const loadedMetadata = new Promise(resolve => {
    video.onloadedmetadata = () => {
      window.URL.revokeObjectURL(video.src);
      videoForm.value.width = video.videoWidth;
      videoForm.value.height = video.videoHeight;
      videoForm.value.duration = video.duration; // 获取视频时长
      form.value.duration = formatDuration(video.duration); // 将时长格式化并赋值给表单
      resolve();
    };
  });

  await loadedMetadata;

  // 计算文件的 MD5 值
  const reader = new FileReader();
  const md5Promise = new Promise(resolve => {
    reader.onload = () => {
      let spark = new SparkMD5.ArrayBuffer();
      spark.append(reader.result);
      videoForm.value.identifier = spark.end(false); // 保存 MD5 值
      resolve(videoForm.value.identifier);
    };
  });
  reader.readAsArrayBuffer(file);

  await md5Promise;

  // 检查文件是否已经存在（秒传）
  const response = await testUploadVideo({ fileMd5: videoForm.value.identifier });
  if (response.msg === "文件已存在，秒传成功") {
    form.value.md5 = videoForm.value.identifier;
    videoUpload.value.abort(file);
    return false;  // 阻止上传
  } else {
    return true;   // 允许上传
  }
}

// 分片上传逻辑，修复进度条问题
function chunkedUpload({ file }) {
  const totalSize = file.size;
  const chunkCount = Math.ceil(totalSize / (5 * 1024 * 1024)); // 每个分片5MB
  const totalChunks = ref(chunkCount); // 分片总数
  completedChunks.value = 0; // 已完成分片数

  const uploadPromises = [];

  // 上传分片
  for (let i = 0; i < chunkCount; i++) {
    const start = i * (5 * 1024 * 1024);
    const end = Math.min((i + 1) * (5 * 1024 * 1024), totalSize);
    const chunk = file.slice(start, end);
    const formData = new FormData();
    formData.append('file', chunk);
    formData.append('filename', file.name);
    formData.append('totalChunks', chunkCount);
    formData.append('chunkNumber', i);
    formData.append('identifier', videoForm.value.identifier); // 添加文件的MD5值作为参数

    const uploadPromise = uploadChunk(formData, (progressEvent) => {
      // 更新上传进度
      uploadPercentage.value = Math.min(
        100,
        Math.max(0, Math.round(((completedChunks.value + progressEvent.loaded / progressEvent.total) / totalChunks.value) * 100))
      );
    }).then(() => {
      completedChunks.value++;
    }).catch(error => {
      console.error('分片上传失败', error);
      ElMessage({
        type: 'error',
        message: '视频上传失败！'
      });
    });

    uploadPromises.push(uploadPromise);
  }

  // 等待所有分片上传完成
  return Promise.all(uploadPromises)
    .then(responses => {
      form.value.md5 = videoForm.value.identifier; // 同时将MD5值赋值给md5字段
      uploadPercentage.value = 100;
      console.log('分片上传完成', responses);
    })
    .catch(error => {
      console.error('分片上传失败', error);
    });
}

// 格式化视频时长为“hh:mm:ss”格式
function formatDuration(seconds) {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = Math.floor(seconds % 60);
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}
/**更新进度*/
function onProgress(event, file) {
  uploadPercentage.value = Math.floor((event.loaded / event.total) * 100);
}
/**上传分片*/
function uploadChunk(formData, onProgress) {
  return axios.post(uploadUrl.value, formData, {
    onUploadProgress: onProgress ,// 添加进度回调,
    headers:{
      Authorization:'Bearer ' + getToken()
    }
  }).then(response => {
    console.log('分片上传成功', response.data)
    completedChunks.value++;
  })
}
/**上传分片失败*/
function onError(error, file, fileList) {
  console.error('上传失败', error)
}
// 取消上传请求
function beforeRemove(file, fileList) {
  videoForm.value.identifier = null
  completedChunks.value = 0;
  return true
}

</script>
<style scoped>
.videoUploadCss :deep(.el-upload-dragger) {
  width: 150px !important;
  height: 150px !important;
}
</style>
